#!bin/sh

echo "Register Op Begin"

function read_dir(){
	str1=`grep -e $2 $1/*.$4|sed s/[[:space:]]//g`
	array=(${str1//\;/ })
	for var in ${array[@]}; do
	    `echo $var|awk -F $3 '{
			a="___";
			b="__();";
			c="extern void ";
			print(c""a""$3"__"$4""b) >> "extern";
			print (a""$3"__"$4""b) >> "call"
		}'`
	done
}

start=$(date +%s)

SEP='[:(,)]'
FILE_EXTERN_CPP='cpp'
FILE_EXTERN_MM='mm'

SHELL_FOLDER=$(dirname $0)'/../../..'
# handle CPU
CPUFILE=$SHELL_FOLDER/source/backend/cpu/CPUOPRegister.cpp
echo "// This file is generated by Shell for ops register\nnamespace MNN {\n#ifdef MNN_CODEGEN_REGISTER" > $CPUFILE
echo "Start Register CPU"
CPU=$SHELL_FOLDER/source/backend/cpu
CPU_KEY='REGISTER_CPU_OP_CREATOR'
read_dir $CPU $CPU_KEY $SEP $FILE_EXTERN_CPP
cat extern >> $CPUFILE
rm extern
echo '\nvoid registerCPUOps() {' >> $CPUFILE
cat call >> $CPUFILE
echo '}\n#endif\n}' >> $CPUFILE
rm call

# handle Shape
echo "Start Register Shape"
SHAPEFILE=$SHELL_FOLDER/source/shape/ShapeRegister.cpp
SHAPE=$SHELL_FOLDER/source/shape
SHAPE_KEY="REGISTER_SHAPE"
echo "// This file is generated by Shell for ops register\nnamespace MNN {\n#ifdef MNN_CODEGEN_REGISTER" > $SHAPEFILE
read_dir $SHAPE $SHAPE_KEY $SEP $FILE_EXTERN_CPP
cat extern >> $SHAPEFILE
rm extern
echo '\nvoid registerShapeOps() {' >> $SHAPEFILE
cat call >> $SHAPEFILE
echo '}\n#endif\n}' >> $SHAPEFILE
rm call

echo "Register Op End"

dur=$(echo "$(date +%s) - $start" | bc)
printf "Execution time: %.6f seconds" $dur
